package com.hangzhou.xyj.ui.adapter.base;

import android.content.Context;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.hangzhou.xyj.R;
import com.hangzhou.xyj.net.listener.HttpResponseListener;
import com.hangzhou.xyj.ui.dialog.LoadingDialog;
import com.hangzhou.xyj.ui.widget.views.MyRecyclerView;
import com.hangzhou.xyj.utils.StringUtil;
import com.hangzhou.xyj.utils.ToastUtil;
import com.hangzhou.xyj.utils.constants.Constants;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by sunwei on 2015/12/4.
 * Email: lx_sunwei@163.com.
 * Description: recycleView 滑动到底部加载更多
 */
public abstract class BaseLoadingAdapter<T> extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    //正常条目
    protected static final int TYPE_NORMAL_ITEM = 0;
    //加载条目
    protected static final int TYPE_LOADING_ITEM = -1;
    private static final String TAG = "BaseLoadingAdapter";
    //是否正在加载
    public boolean mIsLoading = false;
    //数据集
    public List<T> mDataList;
    public LayoutInflater mLayoutInflater;
    protected Context mContext;
    protected int mIntentTag;
    //加载viewHolder
    private LoadingViewHolder mLoadingViewHolder;
    //瀑布流
    private StaggeredGridLayoutManager mStaggeredGridLayoutManager;
    //首次进入
//    private boolean mFirstEnter = true;
    private RecyclerView mRecyclerView;
    private int mLastListSize = 0;//上一次的长度
    private boolean isLoadMore = false;//是否是加载更多
    private boolean isNoMore = false;//没有更多了
    private LoadingDialog mLoadingDialog;

    private int mCurrentPage;//当前页码

    private int mPageSize = Constants.PAGE_SIZE;//页面条目数

    private int mAdditionalSize;//额外的ViewHolder

    private boolean isReload;//是否是重新加载
    private OnLoadingListener mOnLoadingListener;

    public BaseLoadingAdapter() {
    }

    public BaseLoadingAdapter(RecyclerView recyclerView, List<T> dataList) {
        if (dataList == null) {
            dataList = new ArrayList<>();
        }
        mDataList = dataList;

        mRecyclerView = recyclerView;

        setSpanCount(recyclerView);

        mContext = recyclerView.getContext();

        mLayoutInflater = LayoutInflater.from(mContext);
        //notifyLoading();
    }

    protected void setAdditionalSize(int size) {
        this.mAdditionalSize = size;
    }

    public int getIntentTag() {
        return mIntentTag;
    }

    public void setIntentTag(int mIntentTag) {
        this.mIntentTag = mIntentTag;
    }

    /**
     * 获取当前页码
     *
     * @return
     */
    public int getCurrentPage() {
        mPageSize = Constants.PAGE_SIZE;
        mCurrentPage = ((getItemCount() - 1) / Constants.PAGE_SIZE) + 1;
        return mCurrentPage;
    }

    public void setmPageSize(int mPageSize) {
        this.mPageSize = mPageSize;
    }

    /**
     * 获取当前页码
     *
     * @return
     */
    public int getCurrentPage(int pageSize) {
        mPageSize = pageSize;
        mCurrentPage = (getItemCount() / pageSize) + 1;
        return mCurrentPage;
    }

    /**
     * 刷新数据
     *
     * @param newDataList
     */
    public void update(List<T> newDataList) {
        //为null加载失败情况
        if (newDataList == null) {
            setLoadingError();
            notifyDataSetChanged();
            return;
        }

        //size = 0 或者 加载过来的还是原来的 没有更多了情况
        if (!isReload && (newDataList.isEmpty() || (getItemCount() - 1) % mPageSize == newDataList.size())) {
            setLoadingNoMore();
//            notifyDataSetChanged();
            return;
        }

        //有更多情况
        if (isLoadMore) {
            mDataList.remove(mDataList.size() - 1);
            isLoadMore = false;
        }
        mLastListSize = mDataList.size();
        this.mDataList.addAll(newDataList);
        setLoadingComplete();
        notifyItemChanged(mLastListSize);
    }

    public void load(List<T> newDataList) {
        //为null加载失败情况
        if (newDataList == null) {
            setLoadingError();
            notifyDataSetChanged();
            return;
        }

        //size = 0 没有更多了情况
        if (!isReload && (newDataList.isEmpty() || (getItemCount() - mAdditionalSize - 1) % mPageSize == newDataList.size())) {
//            notifyLoading();
            setLoadingNoMore();
//            notifyDataSetChanged();
            return;
        }
        this.mDataList = newDataList;
        setLoadingComplete();
        notifyDataSetChanged();
    }

    public void setIsReload(boolean isReload) {
        this.isReload = isReload;
    }

    /**
     * 设置监听接口
     *
     * @param onLoadingListener onLoadingListener
     */
    public void setOnLoadingListener(OnLoadingListener onLoadingListener) {
        setScrollListener(mRecyclerView);
        mOnLoadingListener = onLoadingListener;
    }

    public boolean getIsNoMore() {
        return this.isNoMore;
    }

    /**
     * @param
     * @return
     * @author yaohuix
     * @date 2016/3/17 14:29
     */
    public void setIsNoMore(boolean isNoMore) {
        this.isNoMore = isNoMore;
    }

    /**
     * 加载完成，隐藏 footerView
     */
    private void setLoadingComplete() {
        if (isNoMore) {
            mRecyclerView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    notifyItemRemoved(mDataList.size() - 1);
                    mDataList.remove(mDataList.size() - 1);
                    mIsLoading = false;
                    isNoMore = false;//还原
                }
            }, 1100);
            return;
        }
        if (mDataList.size() > 0 && mDataList.get(mDataList.size() - 1) != null) {
            mIsLoading = false;
            notifyItemChanged(mDataList.size() - 1);
        }
    }

    /**
     * 没有更多数据
     */
    public void setLoadingNoMore() {
        mIsLoading = false;
        if (mLoadingViewHolder != null) {
            mLoadingViewHolder.progressBar.setVisibility(View.GONE);
            mLoadingViewHolder.tvLoading.setText("没有更多了！");
        }
    }

    /**
     * 加载失败
     */
    public void setLoadingError() {
        if (mLoadingViewHolder != null) {
            mIsLoading = false;
            mLoadingViewHolder.progressBar.setVisibility(View.GONE);
            mLoadingViewHolder.tvLoading.setText("加载失败，点击重新加载！");

            mLoadingViewHolder.tvLoading.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mOnLoadingListener != null) {
                        mIsLoading = true;
                        mLoadingViewHolder.progressBar.setVisibility(View.VISIBLE);
                        mLoadingViewHolder.tvLoading.setText("正在加载...");

                        mOnLoadingListener.loading();
                    }
                }
            });
        }
    }

    /**
     * @return Whether it is possible for the child view of this layout to
     * scroll up. Override this if the child view is a custom view.
     */
    private boolean canScrollDown(RecyclerView recyclerView) {
        return ViewCompat.canScrollVertically(recyclerView, 1);
    }

    /**
     * 设置加载item占据一行
     *
     * @param recyclerView recycleView
     */
    private void setSpanCount(RecyclerView recyclerView) {
        RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();

        if (layoutManager == null) {
            Log.e(TAG, "LayoutManager 为空,请先设置 recycleView.setLayoutManager(...)");
        }

        //网格布局
        if (layoutManager instanceof GridLayoutManager) {
            final GridLayoutManager gridLayoutManager = (GridLayoutManager) layoutManager;
            gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    int type = getItemViewType(position);
                    if (type == TYPE_NORMAL_ITEM) {
                        return 1;
                    } else {
                        return gridLayoutManager.getSpanCount();
                    }
                }
            });
        }

        //瀑布流布局
        if (layoutManager instanceof StaggeredGridLayoutManager) {
            mStaggeredGridLayoutManager = (StaggeredGridLayoutManager) layoutManager;
        }
    }

    /**
     * 显示加载
     */
    private void notifyLoading() {
        if (mDataList.size() != 0 && mDataList.get(mDataList.size() - 1) != null) {
            mDataList.add(mDataList.size(), null);//8
            notifyItemInserted(mDataList.size() + mAdditionalSize);
            isLoadMore = true;
            //开始加载更多：平滑滚动到底部
            mRecyclerView.scrollToPosition(mDataList.size());
        }
    }

    /**
     * 监听滚动事件
     *
     * @param recyclerView recycleView
     */
    private void setScrollListener(RecyclerView recyclerView) {
        if (recyclerView == null) {
            Log.e(TAG, "recycleView 为空");
            return;
        }
        if (!(recyclerView instanceof MyRecyclerView)) {
            Log.e(TAG, "recycleView is not MyRecyclerView");
            return;
        }
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (!canScrollDown(recyclerView)) {//不能往下滚动
                    //首次进入不加载
                    if (!mIsLoading && dy > 0) {//不是正在加载 非首次进入
                        mIsLoading = true;
                        notifyLoading();
                        if (mLoadingViewHolder != null) {
                            mLoadingViewHolder.progressBar.setVisibility(View.VISIBLE);
                            mLoadingViewHolder.tvLoading.setText("正在加载...");
                        }
                        //回调
                        if (mOnLoadingListener != null) {
                            mOnLoadingListener.loading();
                        }
                    }
                }

             /*   if (mFirstEnter) {
                    mFirstEnter = false;
                }*/
            }
        });
    }

    /**
     * 创建viewHolder
     *
     * @param parent viewGroup
     * @return viewHolder
     */
    public abstract RecyclerView.ViewHolder onCreateNormalViewHolder(ViewGroup parent, int viewType);

    /**
     * 绑定viewHolder
     *
     * @param holder   viewHolder
     * @param position position
     */
    public abstract void onBindNormalViewHolder(RecyclerView.ViewHolder holder, int position);

    @Override
    public int getItemViewType(int position) {
        T t = mDataList.get(position);
        if (t == null) {
            return TYPE_LOADING_ITEM;
        } else {
            return TYPE_NORMAL_ITEM;
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == TYPE_LOADING_ITEM) {
            View view = LayoutInflater.from(parent.getContext()).inflate(
                    R.layout.loading_layout, parent, false);
            mLoadingViewHolder = new LoadingViewHolder(view);
            return mLoadingViewHolder;
        } else {
            return onCreateNormalViewHolder(parent, viewType);
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        int type = getItemViewType(position);
        if (type == TYPE_LOADING_ITEM) {
            if (mStaggeredGridLayoutManager != null) {
                StaggeredGridLayoutManager.LayoutParams layoutParams =
                        new StaggeredGridLayoutManager.LayoutParams(
                                ViewGroup.LayoutParams.MATCH_PARENT,
                                ViewGroup.LayoutParams.WRAP_CONTENT);
                layoutParams.setFullSpan(true);

                mLoadingViewHolder.llyLoading.setLayoutParams(layoutParams);
            }
        } else {
            onBindNormalViewHolder(holder, position);
        }
    }

    @Override
    public int getItemCount() {
        return mDataList.size();
    }

    /**
     * 显示加载框
     *
     * @param text 文本
     */
    public void showLoadingDialog(String text) {
        if (mLoadingDialog == null) {
            mLoadingDialog = new LoadingDialog(mContext);
        }
//        //2个有一个show，则可以
//        if (mLoadingDialog.isShowing() || mRefreshLayout.isRefreshing()) {
//            return;
//        }
        if (StringUtil.isNotBlank(text)) {
            mLoadingDialog.setLoadText(text);
        }
        mLoadingDialog.show();
    }

    /**
     * 隐藏加载框
     */
    public void hideLoadingDialog() {
        if (mLoadingDialog == null) {
            return;
        }
        if (mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }


    /**
     * 加载更多接口
     */
    public interface OnLoadingListener {
        void loading();
    }

    /**
     * 加载布局
     */
    private class LoadingViewHolder extends RecyclerView.ViewHolder {
        public ProgressBar progressBar;
        public TextView tvLoading;
        public LinearLayout llyLoading;

        public LoadingViewHolder(View view) {
            super(view);
            progressBar = (ProgressBar) view.findViewById(R.id.progress_loading);
            tvLoading = (TextView) view.findViewById(R.id.tv_loading);
            llyLoading = (LinearLayout) view.findViewById(R.id.lly_loading);
        }
    }

    /**
     * 用于Http请求的监听器
     */
    public abstract class MyHttpResponseListener extends HttpResponseListener {

        @Override
        public void onStart() {
            showLoadingDialog(null);
        }

        @Override
        public void onFail(String msg) {
            hideLoadingDialog();
            if (StringUtil.isNotBlank(msg)) {
                ToastUtil.show(msg);
            }
        }

        @Override
        public void onSuccess(Object model) {
            hideLoadingDialog();
        }

        @Override
        public void onDone(String msg) {
            hideLoadingDialog();
            if (StringUtil.isNotBlank(msg)) {
                ToastUtil.show(msg);
            }
        }

        @Override
        public void onError() {
            hideLoadingDialog();
            ToastUtil.show(mContext.getResources().getString(R.string.tip_net_error));
        }
    }
}
